package com.fresh.api;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fresh.common.annotation.IgnoreAuth;
import com.fresh.dao.VerifyDao;
import com.fresh.entity.AntifraudUser;
import com.fresh.entity.GsCreateEntity;
import com.fresh.entity.GsLoginResult;
import com.fresh.entity.GsRequest;
import com.fresh.entity.YysResultCode;
import com.fresh.entity.YysResultEntity;
import com.fresh.entity.YysResultValidate;
import com.fresh.entity.ZxExternalData;
import com.fresh.entity.ZxExternalSource;
import com.fresh.service.VerifyService;
import com.fresh.utils.HttpRequest;
import com.fresh.utils.HttpUtils;
import com.fresh.utils.PropertiesUtils;
import com.fresh.utils.Sequence;
import com.google.gson.Gson;

/**
 * 运营商接口调用
 * 
 * @author
 * @version 1.0
 * @date 2017年10月26日下午5:40:14 福乐康 Copyright© All Reserved 官方网站：www.flksh.com
 *       未经授权不得进行修改、复制、出售及商业使用
 */
@RequestMapping({ "/yys" })
@Controller
public class YysController {
	private static final Logger log = LoggerFactory.getLogger(YysController.class);

	@Autowired
	private VerifyService verifyService;

	@Autowired
	private VerifyDao verifyDao;

	@IgnoreAuth
	@RequestMapping({ "toYys" })
	public String toYys(HttpServletRequest request, AntifraudUser user) throws Exception {
		log.info("#toYys()进入运营商查询页！");
		return "/buyer/yys";
	}

	@IgnoreAuth
	@RequestMapping({ "loginYys" })
	public String loginYys(HttpServletRequest request, GsRequest gsRequest,HttpServletResponse response) throws Exception {
		log.info("#loginYys() 开始登录运营商！");
		Gson gson = new Gson();
		
		try {
			
		
		ZxExternalData zxExternalData=null;
		if (request.getSession().getAttribute("USER_SCORE")!=null) {
			 zxExternalData=(ZxExternalData) request.getSession().getAttribute("USER_SCORE");
			
			log.info("#getGs() 当前用户:" + gson.toJson(zxExternalData));
		}else{
			 PrintWriter out = response.getWriter();  
		        out.println("<html>");      
		        out.println("<script>");      
		        out.println("window.open ('"+request.getContextPath()+"/index','_top')");      
		        out.println("</script>");      
		        out.println("</html>");    
			return null;
		}
		
		
		// 运营商接口url
		String yys_url = PropertiesUtils.getProperty("ssmh_url");
		String partner_code = PropertiesUtils.getProperty("partner_code");
		String partner_key = PropertiesUtils.getProperty("partner_key");

		// 调用创建任务接口
		String resCreateJson = null;
		String yys_credit_url = yys_url + "task.unify.create/v3";
		Map<String, String> data = new HashMap<String, String>();
		data.put("partner_code", partner_code);
		data.put("partner_key", partner_key);
		data.put("channel_type", "YYS");
		data.put("channel_code", "100000");
		data.put("real_name", gsRequest.getRealName());
		data.put("identity_code", gsRequest.getIdentityCode());
		// 运营商手机号就是账号
		data.put("user_mobile", gsRequest.getUserName());
		HttpRequest httpRequest = HttpRequest.post(yys_credit_url).form(data);
		if (httpRequest.ok()) {
			resCreateJson = httpRequest.body();
			log.info("#loginYys() 调用创建任务接口返回信息：{}" + resCreateJson);
		}
		GsCreateEntity gsCreateEntity = gson.fromJson(resCreateJson, GsCreateEntity.class);
		// 运营维护中
		if (gsCreateEntity.getCode().equals("2502")) {
			request.setAttribute("message", gsCreateEntity.getMessage());
			return "/buyer/yysResult";
		}

		//登录
		String yys_login_url = yys_url + "yys.unify.acquire/v3?partner_code=" + partner_code + "&partner_key=" + partner_key + "&user_name=" + gsRequest.getUserName() + "&user_pass=" + gsRequest.getUserPass() + "&task_id=" + gsCreateEntity.getTask_id() + "&task_stage=INIT&request_type=submit";
		String resLoginJson = HttpUtils.doPostx(yys_login_url, null, null, 3, 10, "utf-8");
		log.info("#loginYys() 1调用登录验证接口:" + resLoginJson);
		GsLoginResult gsLoginResult = gson.fromJson(resLoginJson, GsLoginResult.class);
		YysResultCode yysResultCode = gson.fromJson(resLoginJson, YysResultCode.class);
		
		if (yysResultCode.getCode().equals("112") || yysResultCode.getCode().equals("113") || yysResultCode.getCode().equals("116")) {
			request.setAttribute("message", yysResultCode.getMessage());
			log.info("#loginYys() 1轮询登录结果112:" + gson.toJson(yysResultCode));
			return "/buyer/yysResult";
		}
		if (yysResultCode.getCode().equals("100")) {
			while (true) {
				// 调用登录验证接口：
				Thread.sleep(3000);
				String yys_login2_url = yys_url + "yys.unify.acquire/v3?partner_code=" + partner_code + "&partner_key=" + partner_key + "&user_name=" + gsRequest.getUserName() + "&user_pass=" + gsRequest.getUserPass() + "&task_id=" + gsCreateEntity.getTask_id() + "&task_stage=INIT&request_type=query";
				String resLoginJson2 = HttpUtils.doPostx(yys_login2_url, null, null, 3, 10, "utf-8");
				log.info("#loginYys() 2调用登录验证接口:" + resLoginJson2);
				yysResultCode = gson.fromJson(resLoginJson2, YysResultCode.class);

				if (yysResultCode.getCode().equals("112") || yysResultCode.getCode().equals("113") || yysResultCode.getCode().equals("116") || yysResultCode.getCode().equals("124") || yysResultCode.getCode().equals("2006")) {
					request.setAttribute("message", yysResultCode.getMessage());
					log.info("#loginYys() 2轮询登录结果112:" + resLoginJson2);
					return "/buyer/yysResultFalse";
				}
				// 105获取验证码轮询
				if (yysResultCode.getCode().equals("105")) {
					YysResultValidate yysResultValidate = gson.fromJson(resLoginJson2, YysResultValidate.class);
					request.setAttribute("task_id", yysResultValidate.getTask_id());
					request.setAttribute("task_stage", yysResultValidate.getData().getNext_stage());
					request.setAttribute("request_type", "submit");
					log.info("#loginYys() 轮询登录结果105:" + resLoginJson2);
					return "/buyer/yysResultValidate";

				}

				if (yysResultCode.getCode().equals("2007")) {
					// 调用查询结果接口：
					String yys_result_url = yys_url + "task.unify.query/v3?partner_code=" + partner_code + "&partner_key=" + partner_key + "&task_id=" + gsLoginResult.getTask_id();
					String resResultJson = HttpUtils.doPostx(yys_result_url, null, null, 3, 10, "utf-8");
					YysResultEntity yysResultEntity = gson.fromJson(resResultJson, YysResultEntity.class);
					log.info("#loginYys() 调用查询结果接口:" + gson.toJson(yysResultEntity));
					// 最后结果入库处理
					setSource(zxExternalData.getId(), resResultJson);
					request.setAttribute("user", yysResultEntity.getData());
					DecimalFormat decimalFormat = new DecimalFormat();
					// 通话详单
					request.setAttribute("callResultList", yysResultEntity.getData().getTask_data().getCall_info().get(0));
					// 账户信息
					request.setAttribute("accountResultList", yysResultEntity.getData().getTask_data().getAccount_info());
					// 个人信息
					request.setAttribute("baseResultList", yysResultEntity.getData().getTask_data().getBase_info());
					log.info("获取数据1"+gson.toJson(yysResultEntity.getData()));
					log.info("获取数据2"+gson.toJson(yysResultEntity.getData().getTask_data()));
					log.info("获取数据3"+gson.toJson(yysResultEntity.getData().getTask_data().getBill_info()));
					log.info("获取数据4"+gson.toJson(yysResultEntity.getData().getTask_data().getFamily_info()));
					log.info("获取数据5"+gson.toJson(yysResultEntity.getData().getTask_data().getSms_info()));
					log.info("获取数据6"+gson.toJson(yysResultEntity.getData().getTask_data().getAccount_info()));
					log.info("获取数据7"+gson.toJson(yysResultEntity.getData().getTask_data().getPoint_info()));
					log.info("获取数据8"+gson.toJson(yysResultEntity.getData().getTask_data().getBase_info()));
					log.info("获取数据9"+gson.toJson(yysResultEntity.getData().getTask_data().getPayment_info()));
					log.info("获取数据10"+gson.toJson(yysResultEntity.getData().getTask_data().getPackage_info()));
					log.info("获取数据11"+gson.toJson(yysResultEntity.getData().getTask_data().getCall_info()));
					
					//运营商扣款
					 verifyService.debit(request, "5");
					return "/buyer/yysResult";
				}
			}
		}
		} catch (Exception e) {
			request.setAttribute("message", "服务器忙，请稍后重试！");
			return "/buyer/yysResult";
		}

		return "/buyer/yysResult";
	}

	@IgnoreAuth
	@RequestMapping({ "getYys" })
	public String getYys(HttpServletRequest request, GsRequest gsRequest,HttpServletResponse response) throws Exception {
		log.info("#getYys() 开始登录验证密码！");
		Gson gson = new Gson();
		
		try {
			
		
		ZxExternalData zxExternalData=null;
		if (request.getSession().getAttribute("USER_SCORE")!=null) {
			 zxExternalData=(ZxExternalData) request.getSession().getAttribute("USER_SCORE");
			
			log.info("#getGs() 当前用户:" + gson.toJson(zxExternalData));
		}else{
			 PrintWriter out = response.getWriter();  
		        out.println("<html>");      
		        out.println("<script>");      
		        out.println("window.open ('"+request.getContextPath()+"/index','_top')");      
		        out.println("</script>");      
		        out.println("</html>");    
			return null;
		}
		
		
		// 运营商接口url
		String yys_url = PropertiesUtils.getProperty("ssmh_url");
		String partner_code = PropertiesUtils.getProperty("partner_code");
		String partner_key = PropertiesUtils.getProperty("partner_key");
		
		Map<String, String> data = new HashMap<String, String>();
		data.put("partner_code", partner_code);
		data.put("partner_key", partner_key);
		data.put("task_id", gsRequest.getTaskId());
		data.put("sms_code", gsRequest.getCode());
		data.put("task_stage", gsRequest.getTaskStage());
		data.put("request_type", "submit");
		
		String yys_login_url = yys_url + "yys.unify.acquire/v3";
		HttpRequest httpRequest = HttpRequest.post(yys_login_url).form(data);
		if (httpRequest.ok()) {
			String resCreateJson = httpRequest.body();
			log.info("#getYys() 验证码登录任务接口返回信息：{}" + resCreateJson);
			GsLoginResult gsLoginResult = gson.fromJson(resCreateJson, GsLoginResult.class);
			if(gsLoginResult.getCode().equals("100")){
				while(true){
					// 调用查询接口：
					Thread.sleep(3000);
					String yys_login2_url =yys_url + "task.unify.query/v3?partner_code=" + partner_code + "&partner_key=" + partner_key + "&task_id=" + gsRequest.getTaskId();
					String resLoginJson2 = HttpUtils.doPostx(yys_login2_url, null, null, 3, 10, "utf-8");
					log.info("#getYys() 105中2调用登录验证接口:" + resLoginJson2);
					YysResultCode yysResultCode = gson.fromJson(resLoginJson2, YysResultCode.class);
					if (yysResultCode.getCode().equals("112") || yysResultCode.getCode().equals("113") || yysResultCode.getCode().equals("116") || yysResultCode.getCode().equals("124") || yysResultCode.getCode().equals("2006")) {
						request.setAttribute("message", yysResultCode.getMessage());
						log.info("#getYys() 105轮询登录结果112:" + resLoginJson2);
						return "/buyer/yysResultFalse";
					}
					
					if(yysResultCode.getCode().equals("2007") || yysResultCode.getCode().equals("0")){
						// 调用查询结果接口：
						String yys_result_url = yys_url + "task.unify.query/v3?partner_code=" + partner_code + "&partner_key=" + partner_key + "&task_id=" + gsRequest.getTaskId();
						String resResultJson = HttpUtils.doPostx(yys_result_url, null, null, 3, 10, "utf-8");
						YysResultEntity yysResultEntity = gson.fromJson(resResultJson, YysResultEntity.class);
						log.info("#getYys() 调用查询结果接口:" + gson.toJson(yysResultEntity));
						// 最后结果入库处理
						setSource(zxExternalData.getId(), resResultJson);
						request.setAttribute("user", yysResultEntity.getData());
						//通话详单
						request.setAttribute("callResultList", yysResultEntity.getData().getTask_data().getCall_info());
						//账户信息
						request.setAttribute("accountResultList", yysResultEntity.getData().getTask_data().getAccount_info());
						//个人信息
						request.setAttribute("baseResultList", yysResultEntity.getData().getTask_data().getBase_info());
						log.info("获取数据1"+gson.toJson(yysResultEntity.getData()));
						log.info("获取数据2"+gson.toJson(yysResultEntity.getData().getTask_data()));
						log.info("获取数据3"+gson.toJson(yysResultEntity.getData().getTask_data().getBill_info()));
						log.info("获取数据4"+gson.toJson(yysResultEntity.getData().getTask_data().getFamily_info()));
						log.info("获取数据5"+gson.toJson(yysResultEntity.getData().getTask_data().getSms_info()));
						log.info("获取数据6"+gson.toJson(yysResultEntity.getData().getTask_data().getAccount_info()));
						log.info("获取数据7"+gson.toJson(yysResultEntity.getData().getTask_data().getPoint_info()));
						log.info("获取数据8"+gson.toJson(yysResultEntity.getData().getTask_data().getBase_info()));
						log.info("获取数据9"+gson.toJson(yysResultEntity.getData().getTask_data().getPayment_info()));
						log.info("获取数据10"+gson.toJson(yysResultEntity.getData().getTask_data().getPackage_info()));
						log.info("获取数据11"+gson.toJson(yysResultEntity.getData().getTask_data().getCall_info()));
						
						//运营商扣款
						 verifyService.debit(request, "5");
						return "/buyer/yysResult";
			}
		}
			}
		}
		
		} catch (Exception e) {
			request.setAttribute("message", "服务器忙，请稍后重试！");
			return "/buyer/yysResult";
		}
		return "/buyer/yysResult";
	}

	// 信息入库
	public void setSource(String externalId, String json) {
		Timestamp now = new Timestamp(System.currentTimeMillis());

		ZxExternalSource zxExternalSource = new ZxExternalSource();
		zxExternalSource.setId(Sequence.nextId());
		// 5：运营商
		zxExternalSource.setType(PropertiesUtils.getProperty("YYS_type"));
		zxExternalSource.setVersion("v3");
		zxExternalSource.setExternalId(externalId);
		zxExternalSource.setDataSource(json);
		zxExternalSource.setIntertype(Integer.valueOf(3));
		zxExternalSource.setCreateTime(now);
		verifyService.saveSource(zxExternalSource);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

	}

}
